package com.hk.commons.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.hk.commons.jackson.annotations.SensitiveField;
import com.hk.commons.util.StringUtils;

import java.io.IOException;

/**
 * 敏感字段序列化
 *
 * @author Kevin
 * @date 2024-11-21 11:25
 */
public class SensitiveSerializer extends StdSerializer<String> {

    private final SensitiveField sensitiveField;

    protected SensitiveSerializer(SensitiveField sensitiveField) {
        super(String.class);
        this.sensitiveField = sensitiveField;
    }

    @Override
    public Class<String> handledType() {
        return String.class;
    }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        String newValue = null;
        if (StringUtils.hasLength(value)) {
            newValue = sensitiveField.value().format(value, sensitiveField);
        }
        if (sensitiveField.replace()) {
            gen.writeString(newValue);
        } else {
            gen.writeString(value);
            String currentName = gen.getOutputContext().getCurrentName();
            gen.writeStringField(currentName.concat("Sensitive"), newValue);
        }

    }
}
